package com.zjy.financialsystemjavafx.controller;

import javafx.fxml.FXML;
import javafx.scene.control.TextField;
import javafx.scene.control.PasswordField;
import javafx.scene.control.Button;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.event.ActionEvent;
import javafx.stage.Stage;
import com.zjy.financialsystemjavafx.service.UserService;

/**
 * 注册界面控制器
 */
public class RegisterController {

    @FXML
    private TextField usernameField;

    @FXML
    private PasswordField passwordField;

    @FXML
    private PasswordField confirmPasswordField;

    @FXML
    private TextField emailField;

    @FXML
    private TextField phoneField;

    @FXML
    private Button registerButton;

    @FXML
    private Button cancelButton;

    /**
     * 处理注册操作
     */
    @FXML
    private void handleRegister(ActionEvent event) {
        String username = usernameField.getText();
        String password = passwordField.getText();
        String confirmPassword = confirmPasswordField.getText();
        String email = emailField.getText();
        String phone = phoneField.getText();

        if (!password.equals(confirmPassword)) {
            Alert alert = new Alert(AlertType.ERROR);
            alert.setTitle("注册错误");
            alert.setHeaderText(null);
            alert.setContentText("两次输入的密码不一致！");
            alert.showAndWait();
            return;
        }
        try {
            boolean success = new UserService().register(username, password, email, phone);
            if (success) {
                Alert alert = new Alert(AlertType.INFORMATION);
                alert.setTitle("注册成功");
                alert.setHeaderText(null);
                alert.setContentText("注册成功，请使用新账号登录！");
                alert.showAndWait();
                ((Stage) registerButton.getScene().getWindow()).close();
            } else {
                Alert alert = new Alert(AlertType.ERROR);
                alert.setTitle("注册失败");
                alert.setHeaderText(null);
                alert.setContentText("注册失败，请检查输入信息！");
                alert.showAndWait();
            }
        } catch (Exception e) {
            e.printStackTrace();
            Alert alert = new Alert(AlertType.ERROR);
            alert.setTitle("注册错误");
            alert.setHeaderText(null);
            alert.setContentText("注册过程中出现异常: " + e.getMessage());
            alert.showAndWait();
        }
    }

    /**
     * 取消并关闭注册窗口
     */
    @FXML
    private void handleCancel(ActionEvent event) {
        ((Stage) cancelButton.getScene().getWindow()).close();
    }
} 